package ycl.security.handler;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Service;
import ycl.common.ApiResult;
import ycl.common.enums.ApiResultEnum;
import ycl.common.utils.ServletUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证失败
 *
 * @author ycl
 * @date 2022-03-10 10:59:09
 */
@Slf4j
@Service("authFailureHandler")
public class AuthFailureHandler implements AuthenticationFailureHandler {
	@Override
	public void onAuthenticationFailure(
			HttpServletRequest request,
			HttpServletResponse response,
			AuthenticationException e) throws IOException {

		ServletUtil.setResultResponse(response);
		ApiResult<Object> result;
		if (e instanceof CredentialsExpiredException) {
			//凭证过期
			result = ApiResult.fail(ApiResultEnum.COLUMN_TEMP_PASSWORD);
		} else {
			result = ApiResult.fail(ApiResultEnum.COLUMN_NOT_KNOW_EXCEPTION);
		}

		response.getWriter().write(JSONObject.toJSONString(result));

	}
}
